package cn.stronglink.asset.terminal.unicom.service;

import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.toolkit.IdWorker;

import cn.stronglink.asset.message.mq.consumer.entity.Reader003Udev;
import cn.stronglink.asset.message.mq.consumer.entity.Reader007DevAddr;
import cn.stronglink.asset.model.AssetBrand;
import cn.stronglink.asset.model.AssetExtMaintenance;
import cn.stronglink.asset.model.AssetModel;
import cn.stronglink.asset.model.AssetType;
import cn.stronglink.asset.model.ItAsset;
import cn.stronglink.asset.model.ItAssetExtPosition;
import cn.stronglink.asset.model.Preset;
import cn.stronglink.asset.model.PresetDetail;
import cn.stronglink.asset.model.PutOn;
import cn.stronglink.asset.model.PutOnDetail;
import cn.stronglink.asset.model.RfidState;
import cn.stronglink.asset.model.TRoom;
import cn.stronglink.asset.module.assetmanage.instock.mapper.AssetExtMaintenanceMapper;
import cn.stronglink.asset.module.assetmanage.instock.mapper.PresetDetailMapper;
import cn.stronglink.asset.module.assetmanage.instock.mapper.PresetMapper;
import cn.stronglink.asset.module.assetmanage.itasset.mapper.ItassetExtPositionMapper;
import cn.stronglink.asset.module.assetmanage.itasset.mapper.ItassetMapper;
import cn.stronglink.asset.module.assetmanage.itasset.vo.ItAssetVo;
import cn.stronglink.asset.module.assetmanage.puton.mapper.PutOnMapper;
import cn.stronglink.asset.module.basicdata.assetBrand.mapper.AssetBrandMapper;
import cn.stronglink.asset.module.basicdata.assetModel.mapper.AssetModelMapper;
import cn.stronglink.asset.module.basicdata.assetType.mapper.AssetTypeMapper;
import cn.stronglink.asset.module.basicdata.tRoom.mapper.TRoomMapper;
import cn.stronglink.asset.module.rfidState.mapper.RfidStateMapper;
import cn.stronglink.asset.module.rfidState.vo.InventoryDiffVo;
import cn.stronglink.asset.module.rfidState.vo.ReaderAntennaDevAddr;
import cn.stronglink.asset.terminal.unicom.param.ArrivalVO;
import cn.stronglink.asset.terminal.unicom.param.DoCheckParam;
import cn.stronglink.asset.terminal.unicom.param.ReturnData;
import cn.stronglink.asset.terminal.unicom.param.UpdateAssetParam;
import cn.stronglink.suite.core.util.PropertiesUtil;
import cn.stronglink.suite.core.util.WebUtil;

@Service
@Transactional(rollbackFor=Exception.class) 
public class ApiService {

	@Autowired
	private ItassetMapper itassetMapper;
	@Autowired
	private PresetDetailMapper presetDetailMapper;
	@Autowired
	private PresetMapper presetMapper;
	@Autowired
	private ItassetExtPositionMapper itassetExtPositionMapper;
	@Autowired
	private AssetExtMaintenanceMapper maintenanceMapper;
	@Autowired
	private PutOnMapper putOnMapper;
	@Autowired
	private TRoomMapper tRoomMapper;
	@Autowired
	private AssetBrandMapper brandMapper;
	@Autowired
	private AssetModelMapper modelMapper;
	@Autowired
	private AssetTypeMapper typeMapper;
	@Autowired
	private RfidStateMapper rfidStateMapper;
	
	/**
	 * 手持端  查询需要验收的列表  
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<PresetDetail> qryTerminalCheckList() {
		return presetDetailMapper.qryTerminalCheckList();
	}
	
	/**
	 * 获取上架单 
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<PutOnDetail> getTerminalPutUpList() {
		return putOnMapper.getTerminalPutUpList();
	}
	
	/**
	 * 联通手持用户验收
	 * @param asset
	 * @throws Exception 
	 */
	public String checkTerminal(List<DoCheckParam> assetList) throws Exception {
		   List<DoCheckParam> rightList =new ArrayList<DoCheckParam>();
		   List<UpdateAssetParam> paramList = new ArrayList<UpdateAssetParam>();
		   for(DoCheckParam paramCheck:assetList){
		    	//判断rfid是否存在
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("rfidNo", paramCheck.getRfidNo().toUpperCase());
				Integer count= itassetMapper.qryAssetByRfidNo(map);
				if(count==0){
				   rightList.add(paramCheck);
				   PresetDetail detail = presetDetailMapper.qryDetailById(paramCheck.getPresetDetailId());
					//插入资产表
				   if(detail!=null){
						//同步CMDB数据库的rfid号
						UpdateAssetParam param = new UpdateAssetParam();
						param.setCmdbId(detail.getCmdbId());
						param.setRfId(paramCheck.getRfidNo().toUpperCase());
						paramList.add(param);
				   }
			    }
		
		     }
		     if(paramList!=null&&paramList.size()>0){
				String jsonParam = JSON.toJSONString(paramList);
				System.out.println(jsonParam+"同步CMDB数据库的rfid号传给uop的数据");
				CloseableHttpClient httpclient = HttpClients.createDefault();
				HttpUriRequest sync = RequestBuilder.post()
						.setUri(new URI(PropertiesUtil.getString("visitUrl")+"resConfirm"))
						.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
						.addParameter("value", jsonParam)	
						.build();
				    CloseableHttpResponse response = httpclient.execute(sync);
					HttpEntity result = response.getEntity();
				try {
					String msg = EntityUtils.toString(result);
					System.out.println(msg+"------------------------同步CMDB数据库的rfid号传给uop的数据-----------------------------");
					ReturnData returnData = JSONObject.parseObject(msg, ReturnData.class);
					System.out.println(returnData.getResultCode()+"------------------------returnData.getResultCode()-----------------------------");
					if(returnData.getResultCode()==1) {
						if(rightList!=null&&rightList.size()>0) {
							System.out.println(returnData.getResultCode()+"------------------------returnData.getResultCode()-----------------------------");
							//创建上架单 
							PutOn putOn = new PutOn();
							putOn.setId(IdWorker.getId());
							putOn.setRoomId(937867483114901504l);
							putOn.setExecuteTime(new Date());
							putOn.setStatus(1);
							putOn.setCreateTime(new Date());
							//添加上架单数据
							putOnMapper.insertPutOn(putOn);	
							
							for(DoCheckParam asset:rightList){
							   PresetDetail detail = presetDetailMapper.qryDetailById(asset.getPresetDetailId());
								//插入资产表
							   if(detail!=null){
									asset.setId(Long.parseLong(detail.getCmdbId().toString()));
									asset.setStatus(1);
									asset.setIsBorrow(false);
									asset.setIsDistribute(false);
									asset.setIsLight(0);
									asset.setSerialNo(detail.getSerialNo());
									asset.setRfidNo(asset.getRfidNo().toUpperCase());
									asset.setAssetName(detail.getAssetName());
									asset.setAssetNo(detail.getAssetNo());
									asset.setBrandId(detail.getBrandId());
									asset.setTypeId(detail.getTypeId());
									asset.setModelId(detail.getModelId());
									asset.setCreateBy(asset.getUserId());
									asset.setCreateTime(new Date());
									asset.setPrice(detail.getPrice());
									asset.setRemark(detail.getRemark());
									itassetMapper.insertItAsset(asset);		
									
									//插入资产扩展表
									ItAssetExtPosition posi= new ItAssetExtPosition();
									posi.setId(IdWorker.getId());
									posi.setAssetId(asset.getId());
									posi.setRackId(asset.getRackId());
									posi.setCreateBy(asset.getUserId());
									posi.setCreateTime(new Date());
									posi.setRoomId(detail.getRoomId());
									itassetExtPositionMapper.insertItAssetExtPosition(posi);
									
									//更新预置详情单为入库
									PresetDetail pd =new PresetDetail();
									pd.setStatus(2);
									pd.setId(asset.getPresetDetailId());
									presetDetailMapper.updatePresetDetail(pd);
									
									List<PresetDetail> detailList = presetDetailMapper.queryDetailList(detail.getPresetId());
									 if(detailList!=null&&detailList.size()>0){
										 boolean isAllComplete=true;
										 for(PresetDetail pdetail:detailList){
											 if(pdetail.getStatus()==1){
												 isAllComplete=false;
											 }
										 }
										 Preset p=new Preset();
										 p.setId(detail.getPresetId());
										 p.setStatus(2);
										 if(isAllComplete){
											 p.setStatus(3);
										 }
										 presetMapper.updatePreset(p);
									 }
									//插入资产扩展表
									 AssetExtMaintenance mainter = new AssetExtMaintenance();
									 mainter.setAssetId(asset.getId());
									 mainter.setId(IdWorker.getId());
									 mainter.setPrice(detail.getPrice());
									 mainter.setContacts(detail.getContacts());
									 mainter.setContactsPhone(detail.getContactsPhone());
									 mainter.setContractNo(detail.getContractNo());
									 mainter.setSupplier(detail.getSupplier());
									 mainter.setExpirationTime(asset.getExpirationTime());
									 mainter.setBuyTime(asset.getBuyTime());
									 mainter.setHotline(asset.getHotline());
									 mainter.setInvoiceNo(asset.getInvoiceNo());
									 mainter.setCreateBy(asset.getUserId());
									 mainter.setCreateTime(new Date());
									 maintenanceMapper.insertAssetExtMaintenance(mainter);
									 
									//增加上架单详情数据
									PutOnDetail pdetail =new PutOnDetail();
									pdetail.setId(IdWorker.getId());
									pdetail.setAssetId(asset.getId());
									pdetail.setStatus(2);//待上架状态
									pdetail.setPutOnId(putOn.getId());
									pdetail.setCreateTime(new Date());
									putOnMapper.insertPutOnDetail(pdetail);	
									
							   }
							}
						}
					
					}else{
						return returnData.getMsg();
					}
				} finally {
					response.close();
					httpclient.close();
				}		
		   }
		
		     return null;
			   
		}
	
	
	/**
	 * 川庆 手持用户验收
	 * @param asset
	 */
	public int cqCheckTerminal(List<DoCheckParam> assetList) {
		for(DoCheckParam asset:assetList){
			//判断rfid是否存在
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("rfidNo", asset.getRfidNo());
			Integer count= itassetMapper.qryAssetByRfidNo(map);
			
			Map<String, Object> map24G = new HashMap<String, Object>();
			map24G.put("24gCode", asset.getRfidNo1());
			Integer count24G= itassetMapper.qryBy24G(map24G);
			if(count24G == 0&&count==0){	
			    PresetDetail detail = presetDetailMapper.qryDetailById(asset.getPresetDetailId());
			    if(detail!=null){
			    	//插入资产表
					asset.setId(IdWorker.getId());
					asset.setStatus(1);
					asset.setIsBorrow(false);
					asset.setIsDistribute(false);
					asset.setIsLight(0);
					asset.setSerialNo(detail.getSerialNo());
					asset.setRfidNo(asset.getRfidNo().toUpperCase());
					asset.setAssetName(detail.getAssetName());
					asset.setAssetNo(detail.getAssetNo());
					asset.setBrandId(detail.getBrandId());
					asset.setTypeId(detail.getTypeId());
					asset.setModelId(detail.getModelId());
					asset.setCreateBy(asset.getUserId());
					asset.setCreateTime(new Date());
					asset.setPrice(detail.getPrice());
					asset.setRemark(detail.getRemark());
					itassetMapper.insertItAsset(asset);		
					
					//插入资产扩展表
					ItAssetExtPosition posi= new ItAssetExtPosition();
					posi.setId(IdWorker.getId());
					posi.setAssetId(asset.getId());
					posi.setRackId(asset.getRackId());
					posi.setCreateBy(asset.getUserId());
					posi.setCreateTime(new Date());
					posi.setRoomId(detail.getRoomId());
					itassetExtPositionMapper.insertItAssetExtPosition(posi);
					
					//更新预置详情单为入库
					PresetDetail pd =new PresetDetail();
					pd.setStatus(2);
					pd.setId(asset.getPresetDetailId());
					presetDetailMapper.updatePresetDetail(pd);
					
					Preset p=new Preset();
					p.setId(detail.getPresetId());
					p.setStatus(3);
					presetMapper.updatePreset(p);
					
					//插入资产扩展表
					 AssetExtMaintenance mainter = new AssetExtMaintenance();
					 mainter.setAssetId(asset.getId());
					 mainter.setId(IdWorker.getId());
					 mainter.setPrice(detail.getPrice());
					 mainter.setContacts(detail.getContacts());
					 mainter.setContactsPhone(detail.getContactsPhone());
					 mainter.setContractNo(detail.getContractNo());
					 mainter.setSupplier(detail.getSupplier());
					 mainter.setExpirationTime(asset.getExpirationTime());
					 mainter.setBuyTime(asset.getBuyTime());
					 mainter.setHotline(asset.getHotline());
					 mainter.setInvoiceNo(asset.getInvoiceNo());
					 mainter.setCreateBy(asset.getUserId());
					 mainter.setCreateTime(new Date());
					 maintenanceMapper.insertAssetExtMaintenance(mainter);

			    }
			  }
		    }
		     return 0;
			   
		}
	
	public void cqDoPutOn(List<PutOnDetail> putOnDetailList) {
		if(putOnDetailList!=null &&putOnDetailList.size()>0){
			//整合上架单详情
			Set<Long> putOnIds=new HashSet<Long>();
			List<PutOnDetail> detailListIdIsNull = new ArrayList<PutOnDetail>();
			for(PutOnDetail putOnDetail:putOnDetailList){
				if(putOnDetail.getPutOnId()!=null){
					//所有的上架单id的集合 (不包含空的id)
					putOnIds.add(putOnDetail.getPutOnId());
				}else{
					//上架单id为空时说明在手持同时执行绑rfid和上架了
					detailListIdIsNull.add(putOnDetail);
				}
			}
			//循环遍历所有的上架详情，如果是上架单id相等，就放在一个上架单里
			Iterator<Long> it = putOnIds.iterator();  
			while (it.hasNext()) {  
			    Long putOnId = it.next();  
			    List<PutOnDetail> list=new ArrayList<PutOnDetail>();
			    for(PutOnDetail d:putOnDetailList){
			    	if(d.getPutOnId()!=null){
						if(d.getPutOnId().longValue()==putOnId||d.getPutOnId().equals(putOnId)){
							list.add(d);
						}
			    	}
				}
			    PutOn p= new PutOn();
			    p.setId(putOnId);
			    p.setDetailList(list);
			    cqDoPutOnOpertaion(p);		
			}
			
			//没有在web端进行绑签直接上架的数据处理
			//先把数据直接执行验收操作 后入上架单  直接上架
			if(detailListIdIsNull!=null&&detailListIdIsNull.size()>0){
				Set<Long> roomIds=new HashSet<Long>();
				for(PutOnDetail d:detailListIdIsNull) {
					roomIds.add(Long.parseLong(d.getRoomId()));
				}
				for(Long roomId:roomIds) {
					PutOn putOn = new PutOn();
					putOn.setId(IdWorker.getId());
					putOn.setExecuteTime(new Date());
					putOn.setOperatorBy(879224697238376448l);
					putOn.setRoomId(roomId);
					putOn.setStatus(3);
					putOn.setCreateBy(WebUtil.getCurrentUser());
					putOn.setCreateTime(new Date());
					//添加上架单数据
					putOnMapper.insertPutOn(putOn);	
					
					for(PutOnDetail detail:detailListIdIsNull){
						if(detail.getRoomId().equals(String.valueOf(roomId))) {
							PresetDetail pdetail = presetDetailMapper.qryDetailById(detail.getPresetDetailId());
							if(pdetail!=null){
								//更新预置详情单为入库
								PresetDetail pd =new PresetDetail();
								pd.setStatus(2);
								pd.setId(detail.getPresetDetailId());
								presetDetailMapper.updatePresetDetail(pd);
								
								Preset p=new Preset();
								p.setId(pdetail.getPresetId());
								p.setStatus(3);
								presetMapper.updatePreset(p);
								
								ItAsset asset = new ItAsset();							
								//插入资产表
								asset.setId(IdWorker.getId());
								asset.setStatus(2);
								asset.setIsBorrow(false);
								asset.setIsDistribute(false);
								asset.setIsLight(0);
								asset.setRfidNo(detail.getRfidNo().toUpperCase());
								asset.setRfidNo1(detail.getRfidNo1());
								asset.setAssetName(pdetail.getAssetName());
								asset.setSerialNo(pdetail.getSerialNo());
								asset.setAssetNo(pdetail.getAssetNo());
								asset.setBrandId(pdetail.getBrandId());
								asset.setTypeId(pdetail.getTypeId());
								asset.setModelId(pdetail.getModelId());
								asset.setCreateTime(new Date());
								itassetMapper.insertItAsset(asset);		
								
								//插入资产扩展表  
								//更新资产表状态为已上架，并且更新资产明细表中 机柜Id 起始U 结束U
								ItAssetExtPosition posi= new ItAssetExtPosition();
								//结束U位计算
								Integer endU=pdetail.getuHeight()+detail.getStartU()-1;
								posi.setId(IdWorker.getId());
								posi.setAssetId(asset.getId());							
								posi.setRoomId(roomId);
								posi.setRackId(Long.parseLong(detail.getRackId()));
								posi.setEnd(endU);
								posi.setStart(detail.getStartU());
								posi.setCreateTime(new Date());
								itassetExtPositionMapper.insertItAssetExtPosition(posi);
								
								//增加上架单详情数据
								detail.setId(IdWorker.getId());
								detail.setStatus(1);//上架状态
								detail.setPutOnId(putOn.getId());
								detail.setAssetId(asset.getId());
								detail.setCreateTime(new Date());
								putOnMapper.insertPutOnDetail(detail);	
								
							}
					
						 }
					}
				}
			}
		}
	}	
	
	private void cqDoPutOnOpertaion(PutOn putOn) {
		putOn.setStatus(3);
		putOn.setUpdateTime(new Date());
		//更新上架单为已完成
		putOnMapper.updatePutOn(putOn);
		
		if(putOn.getDetailList()!=null&&putOn.getDetailList().size()>0){
			for(PutOnDetail detail:putOn.getDetailList()){
				detail.setId(detail.getPutOnDetailId());
				detail.setStatus(1);
				detail.setUpdateTime(new Date());
				putOnMapper.updatePutOnDetail(detail);
				
				//更新资产表状态为已上架，并且更新资产明细表中 机柜Id 起始U 结束U
				ItAsset asset = new ItAsset();
				asset.setId(detail.getAssetId());
				asset.setStatus(2);
				itassetMapper.updateItAsset(asset);
				
				int uHeight = itassetMapper.getUheight(detail.getModelId());
				if(uHeight==0){
					uHeight =1;
				}
				ItAssetExtPosition posi= new ItAssetExtPosition();
				posi.setAssetId(detail.getAssetId());
				posi.setRoomId(Long.parseLong(detail.getRoomId()));
				posi.setRackId(Long.parseLong(detail.getRackId()));
				posi.setStart(detail.getStartU());
				posi.setEnd(detail.getStartU()+uHeight-1);
				itassetExtPositionMapper.updateItAssetExtPosition(posi);	
			}
		}
	}
	
	public String doPutOn(List<PutOnDetail> putOnDetailList) throws Exception {
		if(putOnDetailList!=null &&putOnDetailList.size()>0){
			System.out.println("$$$$$$");
			//整合上架单详情
			Set<Long> putOnIds=new HashSet<Long>();
			List<PutOnDetail> detailListIdIsNull = new ArrayList<PutOnDetail>();
			for(PutOnDetail putOnDetail:putOnDetailList){
				if(putOnDetail.getPutOnId()!=null){
					//所有的上架单id的集合 (不包含空的id)
					putOnIds.add(putOnDetail.getPutOnId());
				}else{
					//上架单id为空时说明在手持同时执行绑rfid和上架了
					detailListIdIsNull.add(putOnDetail);
				}
			}
			//循环遍历所有的上架详情，如果是上架单id相等，就放在一个上架单里
			Iterator<Long> it = putOnIds.iterator();  
			while (it.hasNext()) {  
			    Long putOnId = it.next();  
			    List<PutOnDetail> list=new ArrayList<PutOnDetail>();
			    for(PutOnDetail d:putOnDetailList){
			    	if(!"".equals(String.valueOf(d.getPutOnId()))&&d.getPutOnId()!=null){
						if(d.getPutOnId().longValue()==putOnId||d.getPutOnId().equals(putOnId)){
							list.add(d);
						}
			    	}
				}
			    PutOn p= new PutOn();
			    p.setId(putOnId);
			    p.setDetailList(list);
			    try {
					String aa =this.doPutOnOpertaion(p);
					return aa;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}		
			}
			
			//没有在web端进行绑签直接上架的数据处理
			//先把数据直接执行验收操作 后入上架单  直接上架
			if(detailListIdIsNull!=null&&detailListIdIsNull.size()>0){		
				List<UpdateAssetParam> paramList = new ArrayList<UpdateAssetParam>();
					for(PutOnDetail detail:detailListIdIsNull){
						PresetDetail pdetail = presetDetailMapper.qryDetailById(detail.getPresetDetailId());
						if(pdetail!=null){
							//同步CMDB数据库的设备位置信息
							TRoom room= tRoomMapper.qryRoomNameById(detail.getRoomId());
							ItAsset rackInfo= itassetMapper.qryRackNameById(detail.getRackId());
							UpdateAssetParam param = new UpdateAssetParam();
							param.setCmdbId(pdetail.getCmdbId());
							param.setRfId(detail.getRfidNo());
							param.setStartu(detail.getStartU());
							param.setCountu(pdetail.getuHeight());
							param.setRackName(rackInfo.getAssetName());
							param.setRoomName(room.getName());								
							paramList.add(param);
						}		
					}
				String jsonParam = JSON.toJSONString(paramList);
				System.out.println(jsonParam+"同步CMDB数据库的上架传给uop的数据");
				CloseableHttpClient httpclient = HttpClients.createDefault();
				HttpUriRequest sync = RequestBuilder.post()
						.setUri(new URI(PropertiesUtil.getString("visitUrl")+"resConfirm"))
						.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
						.addParameter("value", jsonParam)	
						.build();
				    CloseableHttpResponse response = httpclient.execute(sync);
					HttpEntity result = response.getEntity();
				try {
					String msg = EntityUtils.toString(result);
					System.out.println(msg+"------------------------同步CMDB数据库的绑签并且上架传给uop的数据-----------------------------");
					ReturnData returnData = JSONObject.parseObject(msg, ReturnData.class);
					System.out.println(returnData.getResultCode()+"------------------------returnData.getResultCode()-----------------------------");
					if(returnData.getResultCode()==1) {
						System.out.println(msg+"------------------------同步CMDB数据库的绑签并且上架传给uop的数据returnData.getResultCode()-----------------------------");
						Set<Long> roomIds=new HashSet<Long>();
						for(PutOnDetail d:detailListIdIsNull) {
							roomIds.add(Long.parseLong(d.getRoomId()));
						}
						
						for(Long roomId:roomIds) {
							PutOn putOn = new PutOn();
							putOn.setId(IdWorker.getId());
							putOn.setRoomId(roomId);
							putOn.setExecuteTime(new Date());
							putOn.setStatus(3);
							putOn.setCreateBy(WebUtil.getCurrentUser());
							putOn.setCreateTime(new Date());
							//添加上架单数据
							putOnMapper.insertPutOn(putOn);	
							
							for(PutOnDetail detail:detailListIdIsNull){
								if(detail.getRoomId().equals(String.valueOf(roomId))) {
									PresetDetail pdetail = presetDetailMapper.qryDetailById(detail.getPresetDetailId());
									//更新预置详情单为入库
									if(pdetail!=null){
										PresetDetail pd =new PresetDetail();
										pd.setStatus(2);
										pd.setId(detail.getPresetDetailId());
										presetDetailMapper.updatePresetDetail(pd);
										
										List<PresetDetail> detailList = presetDetailMapper.queryDetailList(pdetail.getPresetId());
										if(detailList!=null&&detailList.size()>0){
											 boolean isAllComplete=true;
											 for(PresetDetail pdd:detailList){
												 if(pdd.getStatus()==1){
													 isAllComplete=false;
												 }
											 }
											 Preset p=new Preset();
											 p.setId(pdetail.getPresetId());
											 p.setStatus(2);
											 if(isAllComplete){
												 p.setStatus(3);
											 }
											 presetMapper.updatePreset(p);
										}
										
										ItAsset asset = new ItAsset();							
										//插入资产表
										asset.setId(Long.parseLong(pdetail.getCmdbId().toString()));
										asset.setStatus(2);
										asset.setIsBorrow(false);
										asset.setIsDistribute(false);
										asset.setIsLight(0);
										asset.setRfidNo(detail.getRfidNo());
										asset.setAssetName(pdetail.getAssetName());
										asset.setSerialNo(pdetail.getSerialNo());
										asset.setAssetNo(pdetail.getAssetNo());
										asset.setBrandId(pdetail.getBrandId());
										asset.setTypeId(pdetail.getTypeId());
										asset.setModelId(pdetail.getModelId());
										asset.setCreateTime(new Date());
										itassetMapper.insertItAsset(asset);		
										
										//插入资产扩展表  
										//更新资产表状态为已上架，并且更新资产明细表中 机柜Id 起始U 结束U
										ItAssetExtPosition posi= new ItAssetExtPosition();
										//结束U位计算
										int uHeight = pdetail.getuHeight();
										if(uHeight==0){
											uHeight=1;
										}
										Integer endU=uHeight+detail.getStartU()-1;
										posi.setId(IdWorker.getId());
										posi.setAssetId(asset.getId());							
										posi.setRoomId(roomId);
										posi.setRackId(Long.parseLong(detail.getRackId()));
										posi.setEnd(endU);
										posi.setStart(detail.getStartU());
										posi.setCreateTime(new Date());
										itassetExtPositionMapper.insertItAssetExtPosition(posi);
										
										//增加上架单详情数据
										detail.setId(IdWorker.getId());
										detail.setStatus(1);//上架状态
										detail.setPutOnId(putOn.getId());
										detail.setAssetId(asset.getId());
										detail.setCreateTime(new Date());
										putOnMapper.insertPutOnDetail(detail);	
									}		
								}
							}
						}
						
					}else{
						return returnData.getMsg();
					}
				} finally {
					response.close();
					httpclient.close();
				}		
			}
		}else{
			return "上架数据不能为空";
		}
		return null;
		
	}

	private String doPutOnOpertaion(PutOn putOn) throws Exception {
		System.out.println("&&&&&&");
		if(putOn.getDetailList()!=null&&putOn.getDetailList().size()>0){
			List<UpdateAssetParam> paramList = new ArrayList<UpdateAssetParam>();
			for(PutOnDetail detail:putOn.getDetailList()){
				int uHeight = itassetMapper.getUheight(detail.getModelId());
				if(uHeight==0){
					uHeight=1;
				}
				detail.setuHeight(uHeight);
				//同步CMDB数据库的设备位置信息
				TRoom room= tRoomMapper.qryRoomNameById(detail.getRoomId());
				ItAsset rackInfo= itassetMapper.qryRackNameById(detail.getRackId());
				
				UpdateAssetParam param = new UpdateAssetParam();
				param.setCmdbId(detail.getAssetId());
				param.setRfId(detail.getRfidNo());
				param.setStartu(detail.getStartU());
				param.setCountu(uHeight);
				param.setRackName(rackInfo.getAssetName());
				param.setRoomName(room.getName());
				paramList.add(param);		
			}
			String jsonParam = JSON.toJSONString(paramList);
			System.out.println(jsonParam+"同步上架给uop的数据");
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpUriRequest sync = RequestBuilder.post()
					.setUri(new URI(PropertiesUtil.getString("visitUrl")+"resConfirm"))
					.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
					.addParameter("value", jsonParam)	
					.build();
			    CloseableHttpResponse response = httpclient.execute(sync);
				HttpEntity result = response.getEntity();
			try {
				String msg = EntityUtils.toString(result);
				System.out.println(msg+"------------------------同步上架给uop的数据-----------------------------");
				ReturnData returnData = JSONObject.parseObject(msg, ReturnData.class);
				if(returnData.getResultCode()==1) {
					System.out.println(returnData.getResultCode()+"------------------------同步上架给uop的数据-----------------------------");
					List<PutOnDetail> detailList = putOnMapper.queryDetailStatus(putOn.getId());
					if(detailList!=null&&detailList.size()>0){
						 boolean isAllComplete=true;
						 for(PutOnDetail pdd:detailList){
							 if(pdd.getStatus()==2){
								 isAllComplete=false;
							 }
						 }
						 putOn.setStatus(1);
						 putOn.setUpdateTime(new Date());
						 if(isAllComplete){
							 putOn.setStatus(3);
						 }
						//更新上架单为已完成
						putOnMapper.updatePutOn(putOn);
					}
					
					
					for(PutOnDetail detail:putOn.getDetailList()){
						detail.setId(detail.getPutOnDetailId());
						detail.setStatus(1);
						detail.setUpdateTime(new Date());
						putOnMapper.updatePutOnDetail(detail);
						
						//更新资产表状态为已上架，并且更新资产明细表中 机柜Id 起始U 结束U
						ItAsset asset = new ItAsset();
						asset.setId(detail.getAssetId());
						asset.setStatus(2);
						itassetMapper.updateItAsset(asset);
						
						int uHeight = detail.getuHeight();
						if(uHeight==0){
							uHeight=1;
						}
						ItAssetExtPosition posi= new ItAssetExtPosition();
						posi.setRackId(Long.parseLong(detail.getRackId()));
						posi.setAssetId(detail.getAssetId());
						posi.setEnd(detail.getStartU()+uHeight-1);
						posi.setStart(detail.getStartU());
						itassetExtPositionMapper.updateItAssetExtPosition(posi);	
					}
				}else{
					return returnData.getMsg();
				}
			} finally {
				response.close();
				httpclient.close();
			}		
		}
		return null;
		
	}
	
	
	/**
	 * 同步CMDB的到货单
	 * @param arrivalVO
	 */
	public String insertPreset(ArrivalVO arrivalVO) {
		Integer cmdbId = arrivalVO.getId();
		String serialNo  = arrivalVO.getSerialNo();//序列号
		PresetDetail d=presetDetailMapper.qryPresetDetailBySn(serialNo);//查询是否已经同步过该数据
		if(d!=null) {
			return "SN号是"+serialNo+"的设备已经存在";
		}
		String  assetName = arrivalVO.getAssetName();//资产名称
		String  brandName = arrivalVO.getBrandName();//品牌名称
		String modelName = arrivalVO.getModelName();//型号名称
	    String typeName = arrivalVO.getTypeName();//资产类型
	    
	    Preset preset = new Preset();
	    preset.setRoomId(937867483114901505l);
	    Long brandId = brandMapper.getBrandIdByName(brandName);
	    if(brandId==null){
	    	AssetBrand assetBrand = new AssetBrand();
	    	assetBrand.setId(IdWorker.getId());
	    	assetBrand.setName(brandName);
	    	assetBrand.setRemark(brandName);
			assetBrand.setCreateBy(WebUtil.getCurrentUser());
			assetBrand.setCreateTime(new Date());
			brandId=assetBrand.getId();
			brandMapper.insertAssetBrand(assetBrand);
			brandId=assetBrand.getId();
		}
	    
	    Long typeId = typeMapper.getTypeIdByName(typeName);
	    if(typeId==null){
	    	AssetType assetType =new AssetType();
	    	assetType.setId(IdWorker.getId());
	    	assetType.setName(typeName);
	    	assetType.setPid(1l);
	    	assetType.setRack(false);
	    	assetType.setSerial(typeName);
			assetType.setCreateBy(WebUtil.getCurrentUser());
			assetType.setCreateTime(new Date());
			typeId=assetType.getId();
			typeMapper.insertAssetType(assetType);	
		}
	    
	    Long modelId = modelMapper.getModelIdByName(modelName);
	    if(modelId==null){
	    	AssetModel model=new AssetModel();
	    	model.setId(IdWorker.getId());
	    	model.setName(modelName);
	    	model.setBrandId(brandId);
	    	model.setTypeId(typeId);
	    	model.setIsInCabinet(true);
	    	model.setuHeight(arrivalVO.getuHeight());
	    	model.setCreateTime(new Date());
	    	String unityModelPath="Server/standard/standard_1u";
	    	if(arrivalVO.getuHeight()!=null) {
	    		 int i =arrivalVO.getuHeight();
	    	     switch(i){
	    	        case 1:
	    	        	unityModelPath="Server/standard/standard_1u";break;
	    	        case 2:
	    	        	unityModelPath="Server/standard/standard_2u";break;
	    	        case 3:
	    	        	unityModelPath="Server/standard/standard_3u";break;
	    	        case 4:
	    	        	unityModelPath="Server/standard/standard_4u";break;
	    	        case 5:
	    	        	unityModelPath="Server/standard/standard_5u";break;
	    	        case 6:
	    	        	unityModelPath="Server/standard/standard_6u";break;
	    	        case 7:
	    	        	unityModelPath="Server/standard/standard_7u";break;
	    	        case 8:
	    	        	unityModelPath="Server/standard/standard_8u";break;
	    	        case 9:
	    	        	unityModelPath="Server/standard/standard_9u";break;
	    	        case 10:
	    	        	unityModelPath="Server/standard/standard_10u";break;
	    	        case 11:
	    	        	unityModelPath="Server/standard/standard_11u";break;
	    	        case 12:
	    	        	unityModelPath="Server/standard/standard_12u";break;
	    	        case 13:
	    	        	unityModelPath="Server/standard/standard_13u";break;
	    	        case 14:
	    	        	unityModelPath="Server/standard/standard_14u";break;
	    	        case 15:
	    	        	unityModelPath="Server/standard/standard_15u";break;
	    	        case 16:
	    	        	unityModelPath="Server/standard/standard_16u";break;
	    	        case 17:
	    	        	unityModelPath="Server/standard/standard_17u";break;
	    	        case 18:
	    	        	unityModelPath="Server/standard/standard_18u";break;
	    	        case 19:
	    	        	unityModelPath="Server/standard/standard_19u";break;
	    	        case 20:
	    	        	unityModelPath="Server/standard/standard_20u";break;
	    	        case 21:
	    	        	unityModelPath="Server/standard/standard_21u";break;
	    	        case 22:
	    	        	unityModelPath="Server/standard/standard_22u";break;
	    	        case 23:
	    	        	unityModelPath="Server/standard/standard_23u";break;
	    	        case 24:
	    	        	unityModelPath="Server/standard/standard_24u";break;
	    	        case 25:
	    	        	unityModelPath="Server/standard/standard_25u";break;
	    	        case 26:
	    	        	unityModelPath="Server/standard/standard_26u";break;
	    	        case 27:
	    	        	unityModelPath="Server/standard/standard_27u";break;
	    	        case 28:
	    	        	unityModelPath="Server/standard/standard_28u";break;
	    	        case 29:
	    	        	unityModelPath="Server/standard/standard_29u";break;
	    	        case 30:
	    	        	unityModelPath="Server/standard/standard_30u";break;
	    	        case 31:
	    	        	unityModelPath="Server/standard/standard_31u";break;
	    	        case 32:
	    	        	unityModelPath="Server/standard/standard_32u";break;
	    	        case 33:
	    	        	unityModelPath="Server/standard/standard_33u";break;
	    	        case 34:
	    	        	unityModelPath="Server/standard/standard_34u";break;
	    	        case 35:
	    	        	unityModelPath="Server/standard/standard_35u";break;
	    	        case 36:
	    	        	unityModelPath="Server/standard/standard_36u";break;
	    	        case 37:
	    	        	unityModelPath="Server/standard/standard_37u";break;
	    	        case 38:
	    	        	unityModelPath="Server/standard/standard_38u";break;
	    	        case 39:
	    	        	unityModelPath="Server/standard/standard_39u";break;
	    	        case 40:
	    	        	unityModelPath="Server/standard/standard_40u";break;
	    	        case 41:
	    	        	unityModelPath="Server/standard/standard_41u";break;
	    	        case 42:
	    	        	unityModelPath="Server/standard/standard_42u";break;
	    	        default:
	    	        	unityModelPath="Server/standard/standard_1u";break;
	    	      }
	    		model.setUnityModelPath(unityModelPath);
	    		modelId=model.getId();
	    	}
	    	modelMapper.insertAssetModel(model);		
		}
	    
	    preset.setId(IdWorker.getId());
	    preset.setContacts("联通");
	    preset.setContactsPhone("联通电话");
	    preset.setContractNo("联通");
	    preset.setSupplier(brandName);
	    preset.setStatus(1);
	    preset.setCreateTime(new Date());
	    presetMapper.insertPreset(preset);//插入主表
	    
	    PresetDetail presetDetail = new PresetDetail();
	    presetDetail.setId(IdWorker.getId());
	    presetDetail.setPresetId(preset.getId());
	    presetDetail.setAssetName(assetName);
	    presetDetail.setCmdbId(Long.parseLong(cmdbId+""));
	    presetDetail.setSerialNo(serialNo);
	    presetDetail.setTypeId(typeId);
	    presetDetail.setBrandId(brandId);
	    presetDetail.setModelId(modelId);
	    presetDetail.setStatus(1);
	    presetDetail.setRemark("同步到货单");
	    presetDetail.setCreateTime(new Date());
	   
	    presetDetailMapper.insertPresetDetail(presetDetail);//插入子表
	    return null;
	    
	}

	public void sendAntennaData(Reader007DevAddr reader007) throws Exception {
		String rackName = itassetMapper.getRacksNameByDevAddrCode(reader007.getDevAddrCode().toUpperCase());
		if(rackName!=null){
			ReaderAntennaDevAddr addr =new ReaderAntennaDevAddr();
//			addr.setDevAddrCode(rackName);
//			List<ReaderAntennaUdev> list = new ArrayList<ReaderAntennaUdev>();
//			if(reader007.getUdevInfo()!=null&&reader007.getUdevInfo().size()>0){
//				for(Reader007Udev devObj :reader007.getUdevInfo()){
//					ReaderAntennaUdev dev = new ReaderAntennaUdev();
//					dev.setU(devObj.getPosition());
//					list.add(dev);
//				}
//			}
//			addr.setUdevInfo(list);
			String jsonParam = JSON.toJSONString(addr);
			System.out.println(jsonParam+"插拔天线传给uop的数据");
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpUriRequest sync = RequestBuilder.get()
					.setUri(new URI(PropertiesUtil.getString("visitUrl")+"wirePullOut"))
					.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
					.addParameter("value", jsonParam)	
					.build();
			    CloseableHttpResponse response = httpclient.execute(sync);
				HttpEntity result = response.getEntity();
			try {
				String msg = EntityUtils.toString(result);
				System.out.println(msg+"-----------------------插拔天线完成------------------------------");
			} finally {
				response.close();
				httpclient.close();
			}		
		}
	}

	public void inventoryDiff(List<UpdateAssetParam> rackList) throws Exception {
		if(rackList!=null&&rackList.size()>0){
			for(UpdateAssetParam obj :rackList){
				String rackConverCode = itassetMapper.getRackConverCode(obj.getRackName());
				List<InventoryDiffVo> diffentData = new ArrayList<InventoryDiffVo>();
				List<ItAssetExtPosition> diffentPData = new ArrayList<ItAssetExtPosition>();
				if(!"".equals(rackConverCode)&&rackConverCode!=null){
					List<Reader003Udev> list =rfidStateMapper.getAllRfidStateByRack(rackConverCode);
					ItAssetVo positionVo = itassetMapper.getRoomIdByRackConverCode(rackConverCode);
					Long roomId = positionVo.getRoomId();
					String roomName = positionVo.getRoomName();
					Long rackId = positionVo.getRackId();
					if(list!=null&&list.size()>0){
					  for (int i = 0; i < list.size(); i++) {
						Reader003Udev temp =list.get(i);
						
						ItAssetVo vo = itassetMapper.getLedgerU(temp.getRfid());//获取台账信息						
						if(vo !=null){
							//台账u位与实际u位作比较，取得差异的数据传给联通
							if(!rackId.equals(vo.getRackId())||temp.getU()!=(vo.getStartU())){//台账u位与实际u位作比较
								InventoryDiffVo diff = new InventoryDiffVo();
								diff.setCmdbId(vo.getId());
								diff.setRfId(temp.getRfid());
								diff.setRackName(obj.getRackName());
								diff.setRoomName(roomName);
								diff.setStartu(temp.getU());
								diffentData.add(diff);								
								
								//更新库里设备位置信息
								Integer uHeight = 1;
								if(vo.getuHeight()!=null){
									uHeight = vo.getuHeight();
								}
								
								ItAssetExtPosition extPosition = new ItAssetExtPosition();
								extPosition.setAssetId(vo.getId());
								extPosition.setRoomId(roomId);
								extPosition.setRackId(rackId);
								extPosition.setStart(temp.getU());
								extPosition.setEnd(temp.getU()+uHeight-1);
								extPosition.setUpdateTime(new Date());
								diffentPData.add(extPosition);
							}
						}
					}
				  }
				}
				String json1 = JSON.toJSONString(diffentData);
				System.out.println(json1+"盘点差异的数据传给uop的数据************");
				
				if(diffentData!=null&&diffentData.size()>0){
					//发送请求
					String json = JSON.toJSONString(diffentData);
					System.out.println(json+"盘点差异的数据传给uop的数据");
					CloseableHttpClient httpclient = HttpClients.createDefault();
					HttpUriRequest sync = RequestBuilder.post()  
							.setUri(new URI(PropertiesUtil.getString("visitUrl")+"resCheckResult"))
							.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
							.addParameter("value", json)	
							.build();
					    CloseableHttpResponse response = httpclient.execute(sync);
					try {
						 if(200 == response.getStatusLine().getStatusCode()) {  
						    if(diffentPData!=null&&diffentPData.size()>0){
								itassetExtPositionMapper.updateItAssetExtPositionBatch(diffentPData);
							}
						 }  
						
					} finally {
						response.close();
						httpclient.close();
					}
				}
			
			}
		}

	}

	public String getRackInfoCmdb(String rackCode) throws Exception {
		//发送请求
		ItAsset vo = itassetMapper.qryRackNameById(rackCode);//获取台账信息	
		if(vo!=null) {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpUriRequest sync = RequestBuilder.post()  
					.setUri(new URI(PropertiesUtil.getString("visitUrl")+"getResByIdForResRack"))
					.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
					.addParameter("value", vo.getAssetName())	
					.build();
			    CloseableHttpResponse response = httpclient.execute(sync);
				HttpEntity result = response.getEntity();
				try {
					String msg = EntityUtils.toString(result);
					System.out.println(msg+"-----------------------机柜接口完成------------------------------");
					return msg;
					
				} finally {
					response.close();
					httpclient.close();
				}	
		}
		return null; 
	
	}

	public String getServerInfoCmdb(String serverCode)throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpUriRequest sync = RequestBuilder.post()  
				.setUri(new URI(PropertiesUtil.getString("visitUrl")+"getResByIdFor3D"))
				.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
				.addParameter("value", serverCode)	
				.build();
		    CloseableHttpResponse response = httpclient.execute(sync);
			HttpEntity result = response.getEntity();
			try {
				String msg = EntityUtils.toString(result);
				System.out.println(msg+"-----------------------服务器接口完成------------------------------");
				return msg;
				
			} finally {
				response.close();
				httpclient.close();
			}	
	}

}
